package myalert

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type weTOKENJSON struct {
	Access_token string `json:"access_token"`
}

func weGetToken(corpid, corpsecret string) string {
	gettoken_url := "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret
	client := &http.Client{}
	req, _ := client.Get(gettoken_url)
	defer req.Body.Close()
	body, _ := ioutil.ReadAll(req.Body)
	fmt.Printf("\n%q", string(body))
	var mytoken weTOKENJSON
	json.Unmarshal([]byte(body), &mytoken)
	return mytoken.Access_token
}

type weWECHARTMESSAGES struct {
	Touser  string `json:"touser"`
	Msgtype string `json:"msgtype"`
	Agentid string `json:"agentid"`
	Text    struct {
		Content string `json:"content"`
	} `json:"text"`
}

func SendWechart(corpid, corpsecret, agentid, touser, content string) string {
	access_token := weGetToken(corpid, corpsecret)
	send_url := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
	client := &http.Client{}
	msg := weWECHARTMESSAGES{
		Touser:  touser,
		Msgtype: "text",
		Agentid: agentid,
		Text: struct {
			Content string `json:"content"`
		}{Content: content},
	}
	sed_msg, _ := json.Marshal(msg)
	req, _ := http.NewRequest("POST", send_url, bytes.NewBuffer([]byte(sed_msg)))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("charset", "UTF-8")
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("\n%q", string(body))
	return string(body)
}
